package com.thread.lianxi;

import java.util.concurrent.atomic.AtomicInteger;

public class WaitAndNotify extends Thread {

	String name;
	Object preObj;
	Object selfObj;

	public WaitAndNotify(String name, Object selfObj, Object preObj) {
		this.name = name;
		this.preObj = preObj;
		this.selfObj = selfObj;
	}

	@Override
	public void run() {

		AtomicInteger count = new AtomicInteger();
		while (count.get() < 10) {
			synchronized (preObj) {
				synchronized (selfObj) {
					System.out.print(name);
					count.incrementAndGet();
					try {
						Thread.sleep(1);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					selfObj.notify();
				}
				try {
					preObj.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		synchronized (selfObj) {
			selfObj.notify();
		}
	}

	public static void main(String[] args) throws InterruptedException {

		Object a = new Object(), b = new Object(), c = new Object();
		(new WaitAndNotify("B", b, a)).start();
		(new WaitAndNotify("C", c, b)).start();
		(new WaitAndNotify("A", a, c)).start();

	}
}
